package
        link.chengguo.orangemall.single.oms;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import link.chengguo.orangemall.annotation.IgnoreAuth;
import link.chengguo.orangemall.annotation.SysLog;
import link.chengguo.orangemall.component.UserUtils;
import link.chengguo.orangemall.enums.*;
import link.chengguo.orangemall.exception.ApiMallPlusException;
import link.chengguo.orangemall.oms.entity.OmsOrder;
import link.chengguo.orangemall.oms.entity.OmsOrderItem;
import link.chengguo.orangemall.oms.service.IOmsOrderItemService;
import link.chengguo.orangemall.oms.service.IOmsOrderService;
import link.chengguo.orangemall.oms.service.ISysOrderTypeService;
import link.chengguo.orangemall.oms.vo.ConfirmListOrderResult;
import link.chengguo.orangemall.oms.vo.ConfirmOrderResult;
import link.chengguo.orangemall.oms.vo.OrderParam;
import link.chengguo.orangemall.pms.service.IPmsProductConsultService;
import link.chengguo.orangemall.shms.entity.ShmsShopInfo;
import link.chengguo.orangemall.shms.service.IShmsShopCommentLogService;
import link.chengguo.orangemall.shms.service.IShmsShopInfoService;
import link.chengguo.orangemall.single.ApiBaseAction;
import link.chengguo.orangemall.sms.service.ISmsGroupService;
import link.chengguo.orangemall.sys.entity.SysOrderType;
import link.chengguo.orangemall.ums.entity.UmsMember;
import link.chengguo.orangemall.ums.mapper.UmsMemberMapper;
import link.chengguo.orangemall.ums.service.IUmsMemberService;
import link.chengguo.orangemall.utils.CommonResult;
import link.chengguo.orangemall.utils.ValidatorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @Auther:yzb
 * @Date: 2019/12/2 15:02
 * @Description:
 */
@Slf4j
@RestController
@Api(tags = "订单管理", description = "OrderController")
@RequestMapping("/api/oms/order")
public class OrderController extends ApiBaseAction {
    @Resource
    private UmsMemberMapper memberMapper;
    @Resource
    private ISmsGroupService groupService;
    @Resource
    private IOmsOrderService orderService;
    @Resource
    private IOmsOrderItemService orderItemService;
    @Autowired
    private IPmsProductConsultService pmsProductConsultService;
    @Autowired
    private IUmsMemberService memberService;
    @Resource
    private ISysOrderTypeService orderTypeService;
    @Resource
    private IShmsShopInfoService shopInfoService;

    @IgnoreAuth
    @SysLog(MODULE = "oms", REMARK = "查询订单列表")
    @ApiOperation(value = "查询订单列表")
    @GetMapping(value = "/list")
    public Object orderList(OmsOrder order,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        IPage<OmsOrder> page = null;
        order.setMemberId(memberService.getNewCurrentMember().getId());
        Integer status = order.getStatus();
        order.setStatus(null);
        QueryWrapper queryWrapper=new QueryWrapper(order);
        if (status!=null){
            switch (status){
                case 0:
                    //待付款
                     queryWrapper.eq("status", OrderStatus.Default.getValue());
                    break;
                case 1:
                    //待发货

                    queryWrapper.apply(
                            "(status ="+OrderStatus.WaitEnsure.getValue()+//待确认
                                    " or (status="+OrderStatus.Ensured.getValue()//已确认
                                    +" and (" +
                                    "verify_status ="+ VerifyStatus.WaitVerify.getValue()+//待核销
                                    " or express_status="+ ExpressStatus.ToDeliver.getValue()+//待发货
                                    " or (shipping_status <="+ ShippingStatus.ArrivedShop.getValue()//取货之前
                                    +" and shipping_status !=0))))");
                    break;
                case 2://待收货
                    queryWrapper.apply(
                            "status=2 and (verify_status ="+VerifyStatus.Verifyed.getValue()+//已核销
                                    " or express_status="+ExpressStatus.Delivered.getValue()+//已发货
                                    " or shipping_status >"+ShippingStatus.ArrivedShop.getValue()//取货之后
                                    +")");
                    break;
                case 4://已完成/待评价
                    queryWrapper.eq("status",OrderStatus.Finished.getValue());
                    queryWrapper.eq("is_comment",1);
                    break;
                case 6://售后
                    queryWrapper.eq("status",OrderStatus.AfterSale.getValue());
                    break;
                default:
            }
        }
        queryWrapper.orderByDesc("create_time");
        //默认查询非扫码购订单
        if (order.getSendType()==null){
            queryWrapper.ne("send_type", SendType.CodeBuy.getValue());
        }

        page = orderService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<OmsOrder> list = new ArrayList<>();
        for (OmsOrder omsOrder : page.getRecords()) {
            List<OmsOrderItem> itemList = orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", omsOrder.getId()).eq("type", AllEnum.OrderItemType.GOODS.code()));
            omsOrder.setPayTypeName(orderService.getPayTypeName(omsOrder.getPayType()));
            omsOrder.setSourceTypeName(orderService.getSourceTypeName(omsOrder.getSourceType()));
            omsOrder.setStatusName(orderService.getStatusName(omsOrder.getStatus()));
            omsOrder.setPayStatusName(orderService.getPayStatusName(omsOrder.getPayStatus()));
            omsOrder.setExpressStatusName(orderService.getExpressStatusName(omsOrder.getExpressStatus()));
            omsOrder.setShippingStatusName(orderService.getShippingStatusName(omsOrder.getShippingStatus()));
            omsOrder.setPickingStatusName(orderService.getPickingStatusName(omsOrder.getPickingStatus()));
            omsOrder.setVerifyStatusName(orderService.getVerifyStatusName(omsOrder.getVerifyStatus()));
            omsOrder.setAfterSaleStatusName(orderService.getAfterSaleStatusName(omsOrder.getAfterSaleStatus()));
            omsOrder.setIsCommentName(orderService.getIsCommentName(omsOrder.getIsComment()));
            omsOrder.setOrderItemList(itemList);
        }
        return new CommonResult().success(page);
    }


    @IgnoreAuth
    @SysLog(MODULE = "oms", REMARK = "查询扫码购订单列表")
    @ApiOperation(value = "查询扫码购订单列表")
    @GetMapping(value = "/list/codeBuy")
    public Object orderListForCodeBuy(OmsOrder order,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,
                            @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum) {
        IPage<OmsOrder> page = null;
        //status：0-全部，1-待付款，2-待核销，3-已完成，4、售后
        order.setSendType(SendType.CodeBuy.getValue());
        if (ValidatorUtils.empty(order.getStatus())){
            order.setStatus(null);
        }else if(order.getStatus()==1){
            order.setStatus(OrderStatus.Default.getValue());
            order.setPayStatus(PayStatus.WaitPay.getValue());
        }else if(order.getStatus()==2){
            order.setVerifyStatus(VerifyStatus.WaitVerify.getValue());
        }else if(order.getStatus()==3){
            order.setStatus(OrderStatus.Finished.getValue());
        }else if(order.getStatus()==4){
            order.setStatus(OrderStatus.AfterSale.getValue());
        }
        order.setMemberId(memberService.getNewCurrentMember().getId());
        page = orderService.page(new Page<>(pageNum, pageSize), new QueryWrapper<>(order).orderByDesc("create_time"));
        for (OmsOrder omsOrder : page.getRecords()) {
            List<OmsOrderItem> itemList = orderItemService.list(new QueryWrapper<OmsOrderItem>().eq("order_id", omsOrder.getId()).eq("type", AllEnum.OrderItemType.GOODS.code()));
            omsOrder.setOrderItemList(itemList);
        }
        return new CommonResult().success(page);
    }


    @ApiOperation("获取订单详情:订单信息、商品信息、操作记录")
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    @ResponseBody
    public Object detail(@RequestParam(value = "id", required = false, defaultValue = "0") Long id) {
        OmsOrder orderDetailResult = null;
        orderDetailResult = orderService.getById(id);
        ShmsShopInfo shmsShopInfo = shopInfoService.getById(orderDetailResult.getShopId());
        orderDetailResult.setShmsShopInfo(shmsShopInfo);
        OmsOrderItem query = new OmsOrderItem();
        query.setOrderId(id);
        List<OmsOrderItem> orderItemList = orderItemService.list(new QueryWrapper<>(query));
        orderDetailResult.setOrderItemList(orderItemList);
        UmsMember member = memberMapper.selectById(orderDetailResult.getMemberId());
        if (member != null) {
            orderDetailResult.setBlance(member.getBlance());
        }
        return new CommonResult().success(orderDetailResult);
    }

    @SysLog(MODULE = "小程序订单管理", REMARK = "取消订单")
    @ApiOperation("取消订单")
    @RequestMapping(value = "/closeOrder", method = RequestMethod.POST)
    public Object closeOrder(@ApiParam("订单id") @RequestParam Long orderId) {
        try {
            if (ValidatorUtils.empty(orderId)) {
                return new CommonResult().paramFailed("订单参数为空");
            }
            OmsOrder newE = orderService.getById(orderId);
            if (newE.getStatus() != OrderStatus.Default.getValue()) {
                return new CommonResult().paramFailed("订单已支付，请先去申请退款");
            }
            if (orderService.cancelOrder(newE)) {
                return new CommonResult().success();
            }
        } catch (Exception e) {
            return new CommonResult().failed(e.getMessage());
        }
        return new CommonResult().failed();
    }

    @SysLog(MODULE = "订单管理", REMARK = "订单确认收货")
    @ApiOperation("订单确认收货")
    @RequestMapping(value = "/confimDelivery", method = RequestMethod.POST)
    @ResponseBody
    public Object confimDelivery(@ApiParam("订单id") @RequestParam Long id) {
        try {
            return orderService.confimDelivery(id);
        } catch (Exception e) {
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "订单管理", REMARK = "订单确认取货")
    @ApiOperation("订单确认取货")
    @RequestMapping(value = "/confimGet", method = RequestMethod.POST)
    @ResponseBody
    public Object confimGet(@ApiParam("订单id") @RequestParam Long id) {
        try {
            return orderService.confimGet(id);
        } catch (Exception e) {
            return new CommonResult().failed();
        }
    }


    @SysLog(MODULE = "订单管理", REMARK = "订单申请退款")
    @ApiOperation("申请退款")
    @RequestMapping(value = "/applyRefund", method = RequestMethod.POST)
    @ResponseBody
    public Object applyRefund(@ApiParam("订单id") @RequestParam Long id) {
        try {
            return orderService.applyRefund(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("订单确认收货：%s", e.getMessage(), e);
            return new CommonResult().failed();
        }
    }

    @SysLog(MODULE = "oms", REMARK = "添加订单评论")
    @ApiOperation(value = "添加订单评论")
    @PostMapping(value = "/orderevaluate")
    public Object addGoodsConsult(@RequestParam(value = "orderId", defaultValue = "1") Long orderId,
                                  @RequestParam(value = "items", defaultValue = "{}") String items,
                                  @RequestParam(value = "shopInfo", defaultValue = "{}") String shopInfo) throws Exception {

        return orderService.orderComment(orderId, items,shopInfo);
    }

    @ResponseBody
    @ApiOperation(value = "提交订单预览")
    @GetMapping("/submitPreview")
    public Object submitPreview(OrderParam orderParam) {
        try {
            ConfirmOrderResult result = orderService.submitPreview(orderParam);
            return new CommonResult().success(result);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ResponseBody
    @ApiOperation(value = "多店铺预览订单")
    @GetMapping("/submitStorePreview")
    public Object submitStorePreview(OrderParam orderParam) {
        try {
            ConfirmListOrderResult result = orderService.submitStorePreview(orderParam);
            return new CommonResult().success(result);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 团购商品订单预览
     *
     * @param orderParam
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "团购商品订单预览")
    @GetMapping("/preGroupActivityOrder")
    public Object preGroupActivityOrder(OrderParam orderParam) {
        try {
            return orderService.preGroupActivityOrder(orderParam);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 提交订单
     *
     * @param orderParam
     * @return
     */
    @ApiOperation("根据购物车信息生成订单")
    @PostMapping(value = "/generateOrder")
    @ResponseBody
    public Object generateOrder(OrderParam orderParam) {
        try {
            return orderService.generateOrder(orderParam);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("发起拼团")
    @PostMapping(value = "/addGroup")
    @ResponseBody
    public Object addGroup(OrderParam orderParam) {
        try {
            return new CommonResult().success(orderService.addGroup(orderParam));
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @ApiOperation("提交拼团")
    @PostMapping(value = "/acceptGroup")
    @ResponseBody
    public Object acceptGroup(OrderParam orderParam) {
        try {
            return orderService.acceptGroup(orderParam);
        } catch (ApiMallPlusException e) {
            return new CommonResult().failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 订单核销
     * @param code 核销码
     * @param type 核销类型：0-扫码核销，1-输码核销
     * @return
     */
    @ApiOperation("订单核销")
    @PostMapping(value = "/verify")
    @ResponseBody
    public Object verify( @RequestParam(value = "code") String code,
                          @RequestParam(value = "type", defaultValue = "0") Integer type) {
        if (ValidatorUtils.empty(code)){
            return new CommonResult().failed("核销码不能为空！");
        }
        if (type==null){
            type=0;
        }
        return orderService.orderVerify(code,type);
    }


    /**
     * 获取店铺配送模式
     * @return
     */
    @ApiOperation("获取店铺配送模式")
    @GetMapping(value = "/getSendTypes")
    @ResponseBody
    public Object getSendTypes(SysOrderType orderType) {
        if (ValidatorUtils.empty(orderType.getShopId())){
            return new CommonResult().failed("店铺ID不能为空！");
        }
        //根据店铺id查询店铺信息
        ShmsShopInfo shopInfo=shopInfoService.getById(orderType.getShopId());
        if (ValidatorUtils.empty(shopInfo)){
            return new CommonResult().failed("店铺不存在！");
        }
        String[] ids=shopInfo.getDeliveryMode().split(",");
        //查询配送模式
        List<SysOrderType> list=orderTypeService.list(new QueryWrapper<SysOrderType>().in("id",ids));
        Iterator<SysOrderType> it = list.iterator();
        while(it.hasNext()){
            SysOrderType next = it.next();
            if(next.getStatus()==0){
                it.remove();
            }
        }
        return new CommonResult().success(list);
    }



    @ApiOperation("查询用户各分类订单数量")
    @GetMapping(value = "/getOrderNumberForUser")
    @ResponseBody
    public Object getOrderNumberForUser() {
        UmsMember member= UserUtils.getCurrentMember();
        OmsOrder order=new OmsOrder();
        QueryWrapper queryWrapper=null;

        //查询订单总数量
        order.setMemberId(member.getId());
        queryWrapper=new QueryWrapper(order);
        int allCount=orderService.count(queryWrapper);

        //查询待付款订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.eq("status",OrderStatus.Default.getValue());
        int waitPayCount=orderService.count(queryWrapper);

        //查询待发货订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                "(status ="+OrderStatus.WaitEnsure.getValue()+//待确认
                        " or (status="+OrderStatus.Ensured.getValue()//已确认
                        +" and (" +
                        "verify_status ="+VerifyStatus.WaitVerify.getValue()+//待核销
                        " or express_status="+ExpressStatus.ToDeliver.getValue()+//待发货
                        " or (shipping_status <="+ShippingStatus.ArrivedShop.getValue()//取货之前
                        +" and shipping_status !=0))))");
        int waitSendCount=orderService.count(queryWrapper);

        //查询待收货订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.apply(
                "status=2 and (verify_status ="+VerifyStatus.Verifyed.getValue()+//已核销
                        " or express_status="+ExpressStatus.Delivered.getValue()+//已发货
                        " or shipping_status >"+ShippingStatus.ArrivedShop.getValue()//取货之后
                        +")");
        int waitReceiveCount=orderService.count(queryWrapper);

        //查询待评价订单数量
        order.setStatus(OrderStatus.Finished.getValue());
        queryWrapper.eq("status",OrderStatus.Finished.getValue());
        queryWrapper.eq("is_comment",0);
        queryWrapper=new QueryWrapper(order);
        int waitCommentCount=orderService.count(queryWrapper);

        //查询售后订单数量
        queryWrapper=new QueryWrapper(order);
        queryWrapper.eq("status",OrderStatus.AfterSale.getValue());
        int afterSaleCount=orderService.count(queryWrapper);

        Map<String,Integer> map=new HashedMap();
        map.put("allCount",allCount);
        map.put("waitPayCount",waitPayCount);
        map.put("waitSendCount",waitSendCount);
        map.put("waitReceiveCount",waitReceiveCount);
        map.put("waitCommentCount",waitCommentCount);
        map.put("afterSaleCount",afterSaleCount);
        return new CommonResult().success(map);
    }


}
